<script setup>
import { getFeedbackListApi,getStatusFeedbackApi,updateFeedbackStatusApi} from '@/api/admin/feedback'
import {delFeedBackApi,updateFeedBackApi} from '@/api/feedback'
import FeedbackList from '@/components/feedbackList.vue';
import router from '@/router';
import { useUserStore } from '@/stores/user';
import { feedbackType,feedbackStatus, postStatus } from '@/utils/globleVar';
import { postFileApi } from "@/api/file"
import { ElMessageBox,ElMessage } from 'element-plus';
import { onMounted, reactive,watch, ref } from 'vue'
import upImg from "@/components/upImg.vue";
const feedbackList = reactive({
    feedbacks:[],
    pageInfo:{}
})
const userStore = useUserStore()
const userInfo = userStore.userInfo
//------获取反馈列表------------
getFeedbackList(0)
async function getFeedbackList(page){
  try{
    const resp = await getFeedbackListApi(page)
    if(resp.data.code === 200){
      if(page === 0){
        feedbackList.feedbacks = []
      }
      const feedbacks = resp.data.data.content
      feedbackList.pageInfo = resp.data.data.page
      if(feedbacks.length !== 0){
        feedbacks.forEach(feedback =>{
          feedbackList.feedbacks.push(feedback)
        })
      }
    }
  }catch(e){
    console.log(e)
  }
}

//------删除反馈--------------------
   const clickDel = async (feedbackId) =>{
    ElMessageBox.confirm(
        '确认删除？',
        '警告',
        {
          confirmButtonText:'删除',
          cancelButtonText:'取消',
          type:'warning'
        }
      ).then( async()=>{
        try{
        const resp = await delFeedBackApi(feedbackId)
        if(resp.data.code == 200 ){
          feedbackList.values = ['']
          getFeedbackList(0)
          ElMessage.success('删除成功')
        }
        }catch(e){
          console.log(e)
          ElMessage.error(e.message)
        }
      }).catch(()=>{
      })
   }


//取消更新  
const onCancle = ()=>{
    showUpdataBox.value = false
}

//-----------------编辑反馈----------------
const clickEdit = (feedback)=>{
    showUpdataBox.value = true
    showFeedback.value = feedback
}

//点击具体某个反馈要展示的信息
    const showFeedback = ref()
    const showUpdataBox = ref(false)

//图片列中删除已有的某个图片
const delImg = (id)=>{
    const imgsUrl = showFeedback.value.images
    imgsUrl.forEach((img,index)=>{
      if(img.id === id){
        imgsUrl.splice(index,1)
      }
    })
    showFeedback.value.images = imgsUrl
}

//处理添加新图片
const imgFile = ref(FileList)
    const onUpload = (imgFiles)=>{
    imgFile.value = imgFiles
}
    //处理移除新图片
const removeImg = (id)=>{
    imgFile.value.forEach((img,index)=>{
        if(img.uid === id){
            imgFile.value.splice(index,1)
        }
    })
}
//确认更新
const onUpdate =async (imgFiles)=>{
    //构造请求数据
    const updateFeedbackData={
      id:showFeedback.value.id,
      content:showFeedback.value.content,
      contact_name:showFeedback.value.contactName,
      contact_phone:showFeedback.value.contactPhone,
      images:[],
      status:feedbackStatus.unprocessed
    }
    //处理旧图片
    const imageUrlArr = showFeedback.value.images
    imageUrlArr.forEach((oldImg)=>{
        const img = {
            feedback_id:showFeedback.value.id,
            image_url:oldImg.image_url
        }
        updateFeedbackData.images.push(img)
    })
    //处理新图片
    try{
        if(imgFile.value.length !== 0){
            const uploadPromises = imgFile.value.map((file) =>
            postFileApi(file).then((respUpImg) => ({
              feedback_id: showFeedback.value.id,
              image_url: respUpImg.data.data[0],
            }))
            );
            // 等待所有图片上传完成
            const newImages = await Promise.all(uploadPromises);
            newImages.forEach(img=>{
              updateFeedbackData.images.push(img)
            })
        }
    }catch(e){
        ElMessage.error('内部错误，请重试')
        console.log(e)
    }
    //发送更新请求
    try{
      console.log(updateFeedbackData)
      const resp = await updateFeedBackApi(updateFeedbackData)
      if(resp.data.code === 200){
          ElMessage.success('更新反馈成功')
          showUpdataBox.value = false
          imgFile.value = []
      }
    }catch(e){
        console.log(e)
        ElMessage.warning('更新反馈异常，请联系管理员')
    }
}
//----处理下拉框的选择-------------------
const listType = ref('')
const value = ref('ALL')
const handleCommand = async (command) => {
  value.value = command
  return
}
watch(value,async (newValue)=>{
  switch(newValue){
    case 'ALL':
      const respAll = await getFeedbackListApi(0)
      if(respAll.data.code === 200){
        const feedbacks = respAll.data.data.content
        const page = respAll.data.data.page
        feedbackList.feedbacks = []
        feedbackList.pageInfo = {}
        feedbackList.feedbacks = feedbacks
        feedbackList.pageInfo = page
      }
      break
      case 'UNPROCESSED':
      const respUn = await getStatusFeedbackApi(feedbackStatus.unprocessed,0)
      if(respUn.data.code === 200){
        const feedbacks = respUn.data.data.content
        const page = respUn.data.data.page
        feedbackList.feedbacks = []
        feedbackList.pageInfo = {}
        feedbackList.feedbacks = feedbacks
        feedbackList.pageInfo = page
      }
      break
    case 'PROCESSING':
      const respIng = await getStatusFeedbackApi(feedbackStatus.processing,0)
      if(respIng.data.code === 200){
        const feedbacks = respIng.data.data.content
        const page = respIng.data.data.page
        feedbackList.feedbacks = []
        feedbackList.pageInfo = {}
        feedbackList.feedbacks = feedbacks
        feedbackList.pageInfo = page
      }
      break
    case 'PROCESSED':
      const respEd = await getStatusFeedbackApi(feedbackStatus.processed,0)
      if(respEd.data.code === 200){
        const feedbacks = respEd.data.data.content
        const page = respEd.data.data.page
        feedbackList.feedbacks = []
        feedbackList.pageInfo = {}
        feedbackList.feedbacks = feedbacks
        feedbackList.pageInfo = page
      }
      break
  }
})
//--------重新获取反馈列表--------
//value 记录当前选中哪个类型的feedback
const getFeedbackByType =async ()=>{
    var newListResp = {}
    try{
      newListResp = await getFeedbackListApi(0)
    }catch(e){
      console.log(e)
    }
    if(value.value === feedbackStatus.all){
      try{
        newListResp = await  getFeedbackListApi(0)
      }catch(e){
        console.log(e)
      }
    }
    if(value.value === feedbackStatus.unprocessed){
      try{
        newListResp = await getStatusFeedbackApi(feedbackStatus.unprocessed,0)
      }catch(e){
        console.log(e)
      }
    }
    if(value.value === feedbackStatus.processing){
      try{
        newListResp = await  getStatusFeedbackApi(feedbackStatus.processing,0)
      }catch(e){
        console.log(e)
      }
    }
    if(value.value === feedbackStatus.processed){
      try{
        newListResp = await  getStatusFeedbackApi(feedbackStatus.processed,0)
      }catch(e){
        console.log(e)
      }
    }
    return newListResp.data.data
}
//--------修改反馈处理状态---------
const updateStatus =async (id,status)=>{
    try{
        console.log(id)
        console.log(status)
    const resp = await updateFeedbackStatusApi(id,status)
    console.log(resp)
    if(resp.data.code === 200 && feedbackStatus.processing === status){
      ElMessage.success('反馈处理中')
      const data = await getFeedbackByType()
      feedbackList.feedbacks = []
      if(data.content){
        data.content.forEach((feedback)=>{
            feedbackList.feedbacks.push(feedback)
        })
      }
      feedbackList.pageInfo = data.page
    }
    if(resp.data.code === 200 && feedbackStatus.processed === status){
      ElMessage.success('反馈已处理')
      const data = await getFeedbackByType()
      feedbackList.feedbacks = []
      if(data.content){
        data.content.forEach((feedback)=>{
            feedbackList.feedbacks.push(feedback)
        })
      }
      feedbackList.pageInfo = data.page
    }
  }catch(e){
    ElMessage.warning('系统异常，请联系管理员')
    console.log(e)
  }
}
//判断登录用户是否为管理员
const isAdmin = ref(false)
judgeIsAdmin()
function judgeIsAdmin(){
    const roleList = userInfo.roles
    if(roleList.length === 0){
        return ElMessage.warning('您没有角色信息！请联系管理员')
    }
    roleList.forEach(role => {
        if(role.name === 'admin'){
            isAdmin.value = true
        }
    });
   
}
//获取下一页数据
const getMore = async (pageInfo)=>{
    if(pageInfo.totalPages === 1 || pageInfo.number+1 >= pageInfo.totalPages){
        return
    }else{
        getFeedbackList(pageInfo.number+1)
    } 
}
</script>
<template>
    <!-- 下拉菜单 控制获取 所有/已审核  -->
    <el-select
      v-model="listType"
      :change="handleCommand(listType)"
      placeholder="类型选择"
      size="large"
      style="width: 120px">
      <el-option
        v-for="item in feedbackType"
        :key="item.tyep"
        :label="item.name"
        :value="item.tyep"
      />
    </el-select>
    <!-- 更新弹出框 -->
    <el-dialog
        title="修改反馈信息"
        v-model="showUpdataBox">
        <el-form>
            <el-form-item prop="contactName">
                <span>联系人:</span>
                <el-input
                clearable
                placeholder="请输入联系人"
                v-model="showFeedback.contactName"
                ></el-input>
            </el-form-item>
            <el-form-item prop="contactPhone">
                <span>联系电话:</span>
                <el-input
                clearable
                placeholder="请输入电话号码"
                v-model="showFeedback.contactPhone"
                ></el-input>
            </el-form-item>
            <el-form-item prop="summary">
                 <span>反馈内容：</span>
                <el-input
                clearable
                v-model="showFeedback.content"
                type="textarea"
                ></el-input>
            </el-form-item>
            <div class="imgs" v-for="(img,index) in showFeedback.images" :key="index">
                <el-icon
                @click="delImg(img.id)"
                ><CloseBold /></el-icon>
                <img class="img" :src="img.image_url" alt="">
            </div>
            <upImg
            :showConfirm="true"
            @onUpload="onUpload"
            @onUpdate="onUpdate"
            @removeImg="removeImg"
            ></upImg>
            <el-form-item>
                 <el-button
                 @click="onCancle">
                    取消
                </el-button>
            </el-form-item>
        </el-form> 
    </el-dialog>
    <div class="feedback-box">
      <FeedbackList 
      @queryList="getMore"
      @onDel="clickDel"
      @onEdit="clickEdit"
      @onUpdateStatus="updateStatus"
      :isFeedbacktUser="true"
      :showAudit="true"
      :feedbackList="feedbackList">
      </FeedbackList>
    </div>

</template>

<style lang="scss" scoped>
.el-dialog{
  .el-form{
    .el-form-item{
    }
    .imgs{
      .img{
          width: 200px;
          height: 200px;
      }
    }
  }
}
.feedback-box{
  height: 80vh;
  overflow: scroll;
}
::-webkit-scrollbar{
  display: none;
}    
</style>